﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using TestLogMonitor.Common;
using TestLogMonitor.Helper;

namespace TestLogMonitor.Helper
{
    //操作共享盘
    public class ShareDiskHelper
    {
        private const int RESOURCETYPE_DISK = 0x00000001;

        [StructLayout(LayoutKind.Sequential)]
        struct NETRESOURCE
        {
            public int dwScope;
            public int dwType;
            public int dwDisplayType;
            public int dwUsage;
            public string lpLocalName;
            public string lpRemoteName;
            public string lpComment;
            public string lpProvider;
        }
        //调用Window API的辅助类
        //, CharSet = CharSet.Ansi, EntryPoint = "WNetAddConnection2", CallingConvention = CallingConvention.Cdecl
        [DllImport("mpr.dll")]
        static extern int WNetAddConnection2(ref NETRESOURCE retResource, string password, string username, int flags);

        //, CharSet = CharSet.Ansi, EntryPoint = "WNetCancelConnection2", CallingConvention = CallingConvention.Cdecl
        [DllImport("mpr.dll")]
        static extern int WNetCancelConnection2(string name,int flags,bool force);

        //连接共享盘
        public static bool Connect()
        {
            try
            {
                var netResource = new NETRESOURCE
                {
                    dwType = RESOURCETYPE_DISK,
                    lpRemoteName = GlobalInfo.AppConfigs.ShareDiskInfos.Folder
                };
                // 创建网络访问凭据对象
                var result = WNetAddConnection2(ref netResource, SecurityHelper.Decrypt(GlobalInfo.AppConfigs.ShareDiskInfos.Password), GlobalInfo.AppConfigs.ShareDiskInfos.UserName, 0);
                return result == 0 ? true : false;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                throw new Exception(ex.Message);
            }
           
        }
        //断开共享盘
        public static void Disconnect()
        {
            try
            {
                WNetCancelConnection2(GlobalInfo.AppConfigs.ShareDiskInfos.Folder, 0, true);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                throw new Exception(ex.Message);
            }
          
        }
    }
}
